#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.


import urllib
import urllib2
from xml.dom.minidom import parse
import pygtk
import gtk.glade
import os
import thread


class Gownlear:

    def __init__(self):
        self.w_tree = gtk.glade.XML('gownlear.glade', 'window_main')
        self.songs_list = []
        self.current_song_index = 0
        event_dict = {
            'on_window_main_destroy':gtk.main_quit,
            'on_button_add_clicked':self.add_clicked,
            'on_button_download_clicked':self.download_clicked,
            'on_button_download_clicked':self.download_clicked,
            'on_button_clear_clicked':self.clear_clicked,
            }
        self.w_tree.signal_autoconnect(event_dict)
        w_treeview_list = self.w_tree.get_widget('treeview_list')

        column = gtk.TreeViewColumn('Name', gtk.CellRendererText(), text=0)
        column.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
        column.set_fixed_width(150)
        column.set_resizable(True)
        w_treeview_list.append_column(column)
        column = gtk.TreeViewColumn('Progress', gtk.CellRendererProgress(), text=1, value=2)
        column.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
        column.set_fixed_width(20)
        column.set_resizable(True)
        w_treeview_list.append_column(column)
        w_treeview_list.set_model(gtk.ListStore(str, str, int))

    def add_clicked(self, widget):
        url = self.w_tree.get_widget("entry_url").get_text()
        id = url[url.find("v=")+2:len(url)]
        try:
            s = Song(id)
            self.songs_list.append(s)
            w_treeview_list = self.w_tree.get_widget('treeview_list')
            w_treeview_list.get_model().append((s.song_name, '0%', 0))
            self.w_tree.get_widget('statusbar').push(1, 'Song added')
        except urllib2.HTTPError:
            self.w_tree.get_widget('statusbar').push(1, 'Error: Invalid URL')
        self.w_tree.get_widget("entry_url").set_text('')

    def clear_clicked(self, widget):
        self.w_tree.get_widget('treeview_list').get_model().clear()

    def download_clicked(self, widget):
        #hilo = Thread(target=self.down_thread, args=())
        #hilo.start()
        thread.start_new_thread(self.down_thread, ())
        #self.down_thread()

    def sensitive(self, bool):
        self.w_tree.get_widget('button_add').set_sensitive(bool)
        self.w_tree.get_widget('button_clear').set_sensitive(bool)
        self.w_tree.get_widget('button_download').set_sensitive(bool)

    def down_thread(self):
        self.sensitive(False)
        os.chdir(self.w_tree.get_widget('filechooser_folder').get_current_folder())
        self.w_tree.get_widget('statusbar').push(1, 'Downloading...')
        for s in self.songs_list:
            urllib.urlretrieve(s.song_path, s.song_name + '.mp3', reporthook=self.report_hook)
            self.current_song_index += 1
        self.current_song_index = 0
        self.w_tree.get_widget('statusbar').push(1, 'List completed')
        self.sensitive(True)

    def report_hook(self, block_count, block_size, total_size):
        total_kb  = total_size / 1024
        downloaded = block_count * (block_size/1024)

        iter = self.w_tree.get_widget('treeview_list').get_model().get_iter(0)
        self.w_tree.get_widget('treeview_list').props.model[self.current_song_index][1] = str(downloaded*100/total_kb) + '%'
        self.w_tree.get_widget('treeview_list').props.model[self.current_song_index][2] = downloaded*100/total_kb


class Song:

    def __init__(self, id):
        xml = 'http://www.goear.com/files/sst/secm%s.xml' % id
        doc = urllib2.urlopen(xml, None)
        data = parse(doc).documentElement.getElementsByTagName('song')[0]
        doc.close()
        self.song_name = data.attributes.get('artist').value + ' - ' + data.attributes.get('title').value
        self.song_path = data.attributes.get('path').value

    def __str__(self):
        return str(self.song_name)


if __name__ == '__main__':
    g = Gownlear()
    gtk.gdk.threads_init()
    gtk.main()




"""


# Abrir el archivo xml que contiene la informacion
# de la forma http://www.goear.com/files/sst/secmxxyyzz.xml

url_xml = "http://www.goear.com/files/sst/secm" + audio_id + ".xml"
data = None

try:
    xml_doc = urllib2.urlopen(url_xml,data)
    xml_data = parse(xml_doc)
    xml_doc.close()
except urllib2.HTTPError: # Mensaje en caso de error
    print "Error, no se encuentra la informacion necesaria \n\nEsto puede ser provocado por ingresar mal la direccion (Url) del archivo o\ningresar una opcion no valida. Por favor revise la ayuda con --help"
    raise NotImplementedError

# Buscar la linea "song path=" que es la direccion del archivo
node = xml_data.documentElement.getElementsByTagName('song')[0]
song_path = node.attributes.get('path').value
song_name = node.attributes.get('artist').value + ' - ' + node.attributes.get('title').value + '.mp3'

print song_path
print song_name

f = urllib.urlretrieve(song_path, song_name)
"""
